<?php
/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry
 *          Eavay Javay Barnad, Sarogini Muniyandi, Teow Jit Huan
 *
 */

class Membership extends AppModel {
    var $name = "Membership";
    var $belongsTo = array("User","Committee","Role");


    //check whether the user is secretariat for this committee or not?
    function isSecretariat($committee_id,$user_id){
        $this->recursive=-1;
        $r = $this->find('first',array('field'=>'Membership.role_id','conditions'=>array('Membership.committee_id'=>$committee_id,'Membership.user_id'=>$user_id)));   
        $this->recursive=1;
        if ($r['Membership']['role_id'] == 1){return true;}
        else {return false;}
    }
    
    function saveCommittee($committee_id,$user_id,$defaultrole) {
        
        $ddat['committee_id']=$committee_id;
        $ddat['user_id']=$user_id;
        $defaultrole=$this->Role->findByName($defaultrole);
        $ddat['role_id']=$defaultrole['Role']['id'];
        $this->create();
        $this->save($ddat);
    }
    /*
     * to save roles when user is saved together with committees involved
     * $committees list of committee id
     * $userid user id to save
     */ 
    function saveRoles($committees,$oldie,$userid) {
        foreach($committees as $committee) {
            $new_membership = $this->find('first',array('conditions'=>array('Membership.committee_id'=>$committee,'user_id'=>$userid),'fields'=>'Membership.*'));
            $new_membership['Membership']['role_id'] = isset($oldie[$committee])?$oldie[$committee]:2;
            $this->save($new_membership);
        }  
    }

    function MovingUp($Id, $committee_id,$order_id=NULL ){
        if ( $order_id == NULL) {
            $moveUp = $this->query("SELECT order_id FROM memberships WHERE id=".$Id." AND committee_id=".$committee_id ,$cachequeries = false);
            $moveUp_orderid = $moveUp[0]['memberships']['order_id'];
        } else {
            $moveUp_orderid = $order_id;
        }

        if ( $moveUp_orderid == 0 ) {
            $max_order_id = $this->query("SELECT max(order_id) as order_id FROM memberships WHERE committee_id=".$committee_id ,$cachequeries = false);
            $new_order = $max_order_id[0][0]['order_id']+1;
            $this->query("UPDATE memberships SET order_id=".$new_order." WHERE id=".$Id ,$cachequeries = false);
        } else {
            $movedown = $this->query("SELECT id, order_id FROM memberships WHERE committee_id=".$committee_id." AND order_id < ".$moveUp_orderid." ORDER BY order_id DESC LIMIT 1" ,$cachequeries = false);
            if (count($movedown) > 0 ) {
                $this->query("UPDATE memberships SET order_id = ".$movedown[0]['memberships']['order_id']." WHERE id=".$Id ,$cachequeries = false);
                $this->query("UPDATE memberships SET order_id = ".$moveUp_orderid." WHERE id=".$movedown[0]['memberships']['id'] ,$cachequeries = false);
            }//end count
            
        }

    }

    function MovingDown($Id, $committee_id){
        $moveDown = $this->query("SELECT order_id FROM memberships WHERE id=".$Id." AND committee_id=".$committee_id );
        $moveDown_orderid = $moveDown[0]['memberships']['order_id'];
    
        if ( $moveDown_orderid == 0 ) {
            $max_order_id = $this->query("SELECT max(order_id) as order_id FROM memberships WHERE committee_id=".$committee_id);
            $new_order = $max_order_id[0][0]['order_id'] + 1;
            $this->query("UPDATE memberships SET order_id=".$new_order." WHERE id=".$Id);
        } else {
            $moveup = $this->query("SELECT id, order_id FROM memberships WHERE committee_id=".$committee_id." AND order_id > ".$moveDown_orderid." ORDER BY order_id ASC LIMIT 1");

            if (count($moveup) > 0 ) {
                $this->query("UPDATE memberships SET order_id = ".$moveup[0]['memberships']['order_id']." WHERE id=".$Id);
                $this->query("UPDATE memberships SET order_id = ".$moveDown_orderid." WHERE id=".$moveup[0]['memberships']['id']);
            }//end count
            
        }
    }

    /*
     * This Function will run when Total record order_id more then 1
     * and update all the record
     */ 
    function RunReorder($committee){
        if ($committee) {
            $committeeId = $this->query("SELECT id FROM committees WHERE deleted = 0 AND short_name='".$committee."'");
            $total_record = $this->query("SELECT count(id) as total FROM memberships WHERE order_id = 0 AND committee_id=".$committeeId[0]['committees']['id']);
            $total_record = $total_record[0][0]['total'];
            if ( $total_record > 1 ) {
                $records = $this->query("SELECT id FROM memberships WHERE order_id = 0 AND committee_id=".$committeeId[0]['committees']['id']." ORDER BY order_id ASC");
                foreach ( $records as $record ) {
                    $this->movingUp($record['memberships']['id'],$committeeId[0]['committees']['id'], 0 );
                }//end foreach
            }//end total_record
        } //end committee
    }
    
    //this function will detect the duplicated order id and make it unique
    function DistinctOrder($committee_id){
        do{
            $count_each_order=$this->find('all',array('fields'=>array('Membership.id','Membership.order_id','count(Membership.id)-1 as total'),'conditions'=>array('Membership.committee_id'=>$committee_id),'group'=>array('Membership.order_id')));
            $duplicate=array_filter(set::extract($count_each_order,'{n}.0.total'));
            $unique=0;
            if(!empty($duplicate)){
                $a=array_keys($duplicate);
                $unique=1;
                $this->uniqueOrder($committee_id,$count_each_order[$a[0]]);
            }
        }while($unique==1);
            
    }
    
    //make the order id unique
    function uniqueOrder($committee_id,$data){
        $bigger_order=$this->find('all',array('conditions'=>array('Membership.order_id>'.$data['Membership']['order_id'],'Membership.committee_id'=>$committee_id)));
        foreach($bigger_order as $bdata){
            $bdata['Membership']['order_id']=$bdata['Membership']['order_id']+$data[0]['total'];
            $this->save($bdata);
        }
        while($data[0]['total']){
            $same_order=$this->find('first',array('conditions'=>array('Membership.committee_id'=>$committee_id,'Membership.order_id'=>$data['Membership']['order_id'],'not'=>array('Membership.id'=>$data['Membership']['id']))));
            $same_order['Membership']['order_id']=$same_order['Membership']['order_id']+$data[0]['total'];
            $this->save($same_order);
            $data[0]['total']--;
        }
    }
    
}
?>
